package com.iseastar.guojiang.transfer;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;

import com.iseastar.BaseActivity2;
import com.iseastar.dianxiaosan.model.Const;
import com.iseastar.guojiang.app.AppCourierCaptureActivity;
import com.iseastar.guojiang.consts.MsgID;
import com.iseastar.guojiang.logic.AppHttp;
import com.iseastar.guojiang.logic.JSON;
import com.iseastar.guojiang.model.NewParcelBean;
import com.iseastar.guojiang.model.ReqResult;
import com.iseastar.guojiang.model.TransferTodayParcelBean;
import com.iseastar.guojiang.tools.TextWatcherExt;
import com.shouhuobao.station.R;
import com.shouhuobao.take.utils.StringUtils;

import java.util.ArrayList;

import droid.frame.view.xlist.SListView;

/**
 * Created by joker on 2018/1/30.
 * 今日揽收包裹
 */
public class TransferTodayParcelListActivity extends BaseActivity2 implements View.OnClickListener {

    private TransferTodayParcelListAdapter mAdapter = null;
    private SListView mListView = null;
    private EditText mCodeET;//投递编号输入框
    private ArrayList<TransferTodayParcelBean> mList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        showLoadingDialog(null);
        AppHttp.getInstance().courierTodayTransferRecords();
    }

    @Override
    protected void findViewById() {
        setContentView(R.layout.transfer_today_parcel_list);
        super.findViewById();
        getAppTitle().setCommonTitle("今日揽收包裹");
        mCodeET = (EditText) findViewById(R.id.code_et);
        mCodeET.setOnClickListener(this);
        mListView = (SListView) findViewById(R.id.listview);
        findViewById(R.id.scan_iv).setOnClickListener(this);
        mAdapter = new TransferTodayParcelListAdapter(null, getContext(), mListView);
        mListView.setAdapter(mAdapter);
        mCodeET.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                //
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    String keywords = mCodeET.getText().toString();
                    if (isEmpty(keywords)) {
                        mAdapter.setItems(mList, true);
                        // ignore
                    } else {
                        if (isNotEmpty(mCodeET.getText().toString())) {
                            mAdapter.setItems(serachBagCodeParcel(mCodeET.getText().toString()), true);
                        }
                    }
                    return true;
                }
                return false;
            }
        });
        mCodeET.addTextChangedListener(new TextWatcherExt() {
            private Handler handler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    if (msg.what == 99999) {
                        String keywords = mCodeET.getText().toString();
                        if (isEmpty(keywords)) {
                            mAdapter.setItems(mList, true);
                            // ignore
                        } else {
                            if (isNotEmpty(mCodeET.getText().toString())) {
                                mAdapter.setItems(serachBagCodeParcel(mCodeET.getText().toString()), true);
                            }
                        }
                    }
                }
            };

            @Override
            public void afterTextChanged(Editable s) {
                handler.removeMessages(99999);
                handler.sendEmptyMessageDelayed(99999, 500);
            }
        });
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //点击输入框获取焦点
            case R.id.code_et:
                mCodeET.setFocusable(true);
                mCodeET.setFocusableInTouchMode(true);
                mCodeET.requestFocus();
                setSoftInput(mCodeET, true);
                break;
            //点击扫描投递编号
            case R.id.scan_iv:
                Intent intent = new Intent();
                intent.setClass(getContext(), AppCourierCaptureActivity.class);
                startActivityForResult(intent, Const.RequestCode.scan_bag);
                break;
        }
    }

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            //今日揽收包裹记录
            case MsgID.courier_today_tansfer_records:
                cancelLoadingDialog();
                final ReqResult<TransferTodayParcelBean> result = JSON.parseList(msg.obj, TransferTodayParcelBean.class);
                if (checkLoginStatus(result)) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (result.getResultList() == null || result.getResultList().size() == 0) {
                                findViewById(R.id.empty_layout).setVisibility(View.VISIBLE);
                            } else {
                                findViewById(R.id.empty_layout).setVisibility(View.GONE);
                                if (mAdapter == null) {
                                    mAdapter = new TransferTodayParcelListAdapter(result.getResultList(), getContext(), mListView);
                                    mListView.setAdapter(mAdapter);
                                } else {
                                    mAdapter.setItems(result.getResultList(), true);
                                }
                                mList.clear();
                                if (result.getResultList() != null && result.getResultList().size() > 0) {
                                    mList.addAll(result.getResultList());
                                }
                                ArrayList<TransferTodayParcelBean> courierList = mAdapter.getItems();
                                if (courierList != null && courierList.size() > 0) {
                                    int parcelNum = 0;
                                    for (TransferTodayParcelBean bean : courierList) {
                                        parcelNum += bean.getParcelCnt();
                                    }
                                    ((TextView) findViewById(R.id.today_transfer_desc_tv)).setText("共揽收来自" + courierList.size() + "位火箭侠的" + parcelNum + "个包裹");
                                }
                            }
                        }
                    });

                } else {
                    showToast(result.getMessage());
                }
                return true;
            default:
                return super.handleMessage(msg);
        }
    }

    /**
     * 根据投递编号搜索相关的火箭侠和包裹
     *
     * @param bagCode
     */
    private ArrayList<TransferTodayParcelBean> serachBagCodeParcel(String bagCode) {
        if (mList.size() > 0) {
            ArrayList<TransferTodayParcelBean> resultList = new ArrayList<>();
            for (TransferTodayParcelBean bean : mList) {
                //同一个火箭侠中包裹编号和搜索相同的包裹集合
                ArrayList<NewParcelBean> parcelBeans = new ArrayList<>();
                for (NewParcelBean parcelBean : bean.getParcelDtos()) {
                    if (isNotEmpty(parcelBean.getBagCode()) && parcelBean.getBagCode().contains(bagCode)) {
                        parcelBeans.add(parcelBean);
                    }
                }
                if (parcelBeans.size() > 0) {
                    try {
                        //克隆对象
                        TransferTodayParcelBean serachBean = (TransferTodayParcelBean) bean.clone();
                        serachBean.setParcelDtos(parcelBeans);
                        resultList.add(serachBean);
                    } catch (CloneNotSupportedException e) {
                        e.printStackTrace();
                    }
                }
            }
            return resultList;
        }
        return null;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != Activity.RESULT_OK) {
            return;
        }
        if (requestCode == Const.RequestCode.scan_bag) {
            String bagcode = data.getStringExtra("result");
            if (StringUtils.isEmpty(bagcode)) {
                return;
            }
            int index = bagcode.lastIndexOf("=");
            String code2;
            if (index > -1) {
                code2 = bagcode.substring(index + 1, bagcode.length());
            } else {
                code2 = bagcode;
            }
            mCodeET.setText(code2);
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }
}
